// pages/jiance/jiance.js


const app = getApp()

var util = require('../../js/util.js');
var api = require('../../js/api.js');
var strdata = ''
var lock = true
var a6datas = []
var a6i = 0


Page({
    // toGuanli:function(){
    // 	wx.navigateTo({
    // 		url: '/pages/guanli/guanli'
    // 	})
    // },


    /**
     * 页面的初始数据
     */
    data: {

        userInfo: '',

        equconnstate: false, //设备连接状态


        result: '正常',
        temp: 38.0,
        tempF: 0.0,

        company: '摄氏度℃',
        datetime: '',
        countTimer: '',


        //进度条使用
        count2: 1,
        colors: [
            "#5CADFE",
            "#FE9901",
            "#EB4014",
        ],


    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // console.log('========监听页面加载')
        var that = this
        if (api.checkToken()) {


            util.initBluetooth()
            // that.selectComponent("#top").updateData()


            that.putdata()

            that.onShow() //页面样式渲染
            if (app.globalData.equ.mac != null && app.globalData.equ.mac != '') {
                that.connequ()
            } else {

                wx.reLaunch({
                    url: '/pages/shebei/shebei'
                })

            }

            setInterval(function () { //监控连接状态
                // console.log('====>>监控连接状态')
                // 	util.onBLEState()

                that.setData({
                    equconnstate: app.globalData.equconn0
                })
            }, 500)

            setInterval(function () {
                that.setData({
                    datetime: util.formatTime2(new Date())
                })
            }, 1000)

            setInterval(function () {
                if (app.globalData.equ.mac != null && app.globalData.equ.mac != '' && !app.globalData.equconn0) {
                    // util.initBluetooth()
                    // setTimeout(function() {
                    // 	console.log("====>>5000")
                    // }, 5000)
                    that.connequ()
                }
            }, 10000)
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {


    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var that = this
        that.setData({
            count2: 1,

        })

        // 绘制体温展示进度边线
        const ctx = wx.createCanvasContext('canvas0')

        ctx.arc(170, 200, 125, 0.8 * Math.PI, 2.2 * Math.PI, false)
        ctx.setStrokeStyle('#B0C4DE')
        ctx.setLineWidth(8)
        // ctx.fillText('37.0', 120, 0)
        ctx.stroke()
        ctx.draw()

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {


    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        var that = this
        that.onShow()


        //当逻辑执行完后关闭刷新
        wx.stopPullDownRefresh()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },


    // =====================绘制进度条====================

    drawCircle2: function (step, color) {
        console.log('====:' + step + '<>' + color)
        var that = this

        var context = wx.createCanvasContext('canvas', this);
        // 设置渐变
        var gradient = context.createLinearGradient(50, 120, 350, 120);

        context.setTextAlign('center')
        context.setFontSize(20)
        context.setFillStyle(color)
        context.fillText(that.data.result, 170, 140)

        context.setTextAlign('center')
        context.setFontSize(50)
        context.setFillStyle(color)
        context.fillText(that.data.temp, 170, 200)

        context.setLineWidth(8);
        context.setStrokeStyle(color);
        context.setLineCap('round')
        context.beginPath();
        // 参数step 为绘制的圆环周长，从0到2为一周 。 -Math.PI / 2 将起始角设在12点钟位置 ，结束角 通过改变 step 的值确定
        context.arc(170, 200, 125, -1.2 * Math.PI, -1.2 * Math.PI + step * Math.PI, false);
        context.stroke();
        context.draw()
    },
    //绘制进度条2
    countInterval2: function (sp) {

        var that = this
        let index = 0
        // if (sp < 14) {
        // 	index = 0
        // } else if (sp > 17) {
        // 	index = 2
        // } else {
        // 	index = 1
        // }
        if (that.data.result == '正常' || that.data.result == 'Lo') {
            index = 0
        } else if (that.data.result == '发热') {
            index = 1
        } else if (that.data.result == '高热' || that.data.result == 'Hi') {
            index = 2
        }
        if (that.data.result == 'Lo' || that.data.result == 'Hi') {
            that.setData({
                temp: that.data.result,
                result: ''

            })
        }

        if (sp > 42) {
            sp = 42

        }
        console.log('====>>值' + sp)
        // 设置倒计时 定时器 每100毫秒执行一次，计数器count2+1 ,耗时6秒绘一圈
        that.countTimer = setInterval(() => {
            // console.log('开始绘制进度')
            // console.log(that.data.count2)
            if (that.data.count2 <= sp) { //1.4pi=42
                /* 绘制彩色圆环进度条
                注意此处 传参 step 取值范围是0到2，
                所以 计数器 最大值 60 对应 2 做处理，计数器count=60的时候step=2
                */
                that.drawCircle2(that.data.count2 / (60 / 2), that.data.colors[index])
                that.data.count2++;
            } else {
                that.setData({
                    progress_txt: "重新扫描"
                });
                clearInterval(that.countTimer);

            }
        }, 20)
    },

    // ==============================进度条 end=======================


    // 测量体温按钮
    celiang: function () {
        // console.log('========>>点击测量体温')
        var that = this
        if (!that.data.equconnstate) {
            //未连接设备
            that.connequ()
        } else {
            util.sendMsg('IR8A+A5,')

            wx.showToast({
                title: '测量中',
                icon: 'loading',
                mask: true,
                duration: 3000,


            })


        }


    },
    startDraw: function () {
        var that = this

        //开始绘制进度
        that.setData({
            count2: 1
        })


        let num = Math.floor((that.data.temp - 33.8) / 0.21)
        console.log('====================>>>>>>>>>>>>>>>>>数值')
        console.log(num)
        if (num < 1) {
            num = 1
        }

        if (that.data.temp < 34) {
            that.setData({
                result: 'Lo'
            })

        } else if (that.data.temp >= 34 && that.data.temp < 37.3) {
            that.setData({
                result: '正常'
            })
        } else if (that.data.temp >= 37.3 && that.data.temp <= 38) {
            that.setData({
                result: '发热'
            })
        } else if (that.data.temp > 38 && that.data.temp <= 42.9) {
            that.setData({
                result: '高热'
            })
        } else if (that.data.temp > 42.9) {
            that.setData({
                result: 'Hi'
            })
        }

        if (app.globalData.cels) {
            console.log('====>>摄氏度')
            that.putdata()
        } else {
            console.log('====>>华氏度')
            that.setData({
                temp: that.data.tempF
            })
            that.putdata()
        }


        that.countInterval2(num)
    },


    //连接设备
    connequ: function () {
        var that = this
        //获取蓝牙
        console.log('===>>页面路径')
        let uri = getCurrentPages()[0].route
        console.log(uri)
        if (uri == 'pages/jiance/jiance') {
            console.log('====>>获取蓝牙')
            wx.openBluetoothAdapter({

                success: function (res) {
                    //这里执行开启成功的方法

                    console.log('====>>获取蓝牙成功')

                    let equmac = app.globalData.equ.mac
                    console.log(equmac)

                    //不存在绑定的设备信息
                    if (equmac == '' && uri != 'pages/shebei/shebei') {

                        wx.reLaunch({
                            url: '/pages/shebei/shebei'
                        })

                    } else {
                        //存在绑定的设备
                        //建立连接


                        util.connToDid()

                    }

                },

                fail: function (err) {
                    console.log('获取蓝牙失败')
                    console.log(err)
                    console.log('====>弹窗数量')
                    console.log(app.globalData.showModelNum)
                    //这里是，手机的蓝牙关闭状态下，该接口会返回10001，执行fail方法，
                    if (err.errCode == 10001) {
                        if (app.globalData.showModelNum < 2) {


                            app.globalData.showModelNum++
                            wx.showModal({
                                title: '请打开手机蓝牙服务',
                                icon: 'none',
                                duration: 3000,
                                success: function (res) {
                                    if (res.confirm) {
                                        app.globalData.showModelNum--

                                    } else if (res.cancel) {
                                        app.globalData.showModelNum--
                                    }


                                },
                            })
                        }

                    }
                }
            })
        }


        wx.onBLECharacteristicValueChange(function (res) {
            console.log('==========>>>接收到的数据')
            // console.log(res)

            if (lock) {
                lock = false

                let val = util.ab2Ascii(res.value)
                strdata += val

                console.log(strdata)

                if (strdata.indexOf("\n") > -1) {
                    if (strdata.indexOf("A") == 0) {
                        let strdatas = strdata.trim().split("\n")
                        for (var i = 0; i < strdatas.length; i++) {
                            if (strdatas[i].trim().length > 0) {
                                that.dataAnalysis(strdatas[i].trim())
                            }


                        }
                    }

                    strdata = ''

                }
                lock = true
            }
        })

    },

    dataAnalysis: function (str) {
        var that = this

        if (str.trim().length > 0 && str.indexOf("A") == 0) {
            console.log('====>>数据解析:	' + str)

            let result = ''
            let data0 = str.split(",")
            console.log(data0)

            switch (data0[0]) {
                case 'A1': //时间
                    break;
                case 'A2': //声音
                    if (data0[1].split("=")[1].trim() == 'T') {
                        app.globalData.beep = true
                    } else {
                        app.globalData.beep = false
                    }
                    console.log(app.globalData.beep)
                    break;

                case 'A3': //摄氏度
                    if (data0[1].split("=")[1].trim() == 'T') {
                        app.globalData.cels = true
                    } else {
                        app.globalData.cels = false
                    }
                    console.log(app.globalData.cels)
                    break;
                case 'A4': //userid设置

                    break;
                case 'A5':
                    //To 目标温度  Ta=环境温度
                    wx.hideToast()
                    that.setData({
                        temp: util.handleData(parseInt(data0[2].split("=")[1])),
                        tempF: util.ctof(parseInt(data0[2].split("=")[1]))


                    })
                    let a5time = data0[1]
                    if (a5time > 1587600000) {
                        if (that.data.temp >= 34 && that.data.temp < 42.9) {
                            var data = {
                                wxInfoId: app.globalData.users[app.globalData.usersIndex].wxInfoId,
                                tempC: parseFloat(that.data.temp),
                                tempF: parseFloat(that.data.tempF),
                                equMac: app.globalData.equ.mac,
                                cTime: util.formatTime(new Date(parseInt(a5time) * 1000))
                            }

                            api.addWxEwjMsg(JSON.stringify(data))
                        }
                    }

                    console.log('===>>温度')
                    console.log(that.data.temp)
                    that.startDraw()

                    break;
                case 'A6': //历史数据保存
                    console.log('====>>历史数据')

                    let a6time = data0[1]
                    let a6index = data0[2]
                    let a6temp = parseInt(data0[3])
                    let a6status = data0[4]
                    console.log('====>>a6status')
                    console.log(a6status)

                    if (a6status != null && a6status.toUpperCase().indexOf('OK') > -1) {
                        console.log('====>>a6datas')
                        console.log(a6datas)
                        api.addWxEwjMsgs(JSON.stringify(a6datas))
                        a6i = 0
                        a6datas = []
                        var timeOut = setTimeout(function () {
                            console.log("====>>2000")
                        }, 2000)
                        console.log('====>>关闭加载框')
                        wx.hideToast()
                    }

                    if (app.globalData.bindTime > 0 && (app.globalData.bindTime + 2 * 60 * 1000) > new Date().getTime()) {
                        console.log('====>>新绑定的')
                    } else {

                        let a6tempC = util.handleData(a6temp)
                        let a6tempF = util.ctof(a6temp)
                        console.log(a6time + '==' + a6index + '==' + a6temp)
                        if (a6time > 1587600000) {
                            if (a6tempC >= 34 && a6tempC < 42.9 && app.globalData.users.length > a6index && app.globalData.equ.mac.length >
                                0) {

                                var data = {
                                    wxInfoId: app.globalData.users[a6index].wxInfoId,
                                    tempC: parseFloat(a6tempC),
                                    tempF: parseFloat(a6tempF),
                                    equMac: app.globalData.equ.mac,
                                    isHistory: '1',
                                    cTime: util.formatTime(new Date(parseInt(a6time) * 1000))
                                }
                                console.log('====>>a6i' + a6i)
                                a6datas[a6i++] = data

                            }
                        }


                    }


                    break;


                default:
                    console.log('====>>数据格式有误');
                    console.log(app.globalData.equ);
                    if (app.globalData.isA) {
                        util.closeconn(app.globalData.equ.mac)
                    } else {
                        util.closeconn(app.globalData.equ.deviceId)
                    }


                    that.connequ()


                    if (app.globalData.dataerrnum == 0) {
                        app.globalData.dataerrnum++
                        wx.showModal({
                            title: '数据有误',
                            content: '正在重新连接设备，如果仍然未能解决，请尝试重启设备或小程序',
                            showCancel: false,
                            success(res) {
                                if (res.confirm) {
                                    console.log('用户点击确定')
                                    app.globalData.dataerrnum = 0

                                }
                            }
                        })


                    }

                    break;

            }

        }
    },

    putdata: function () {
        var that = this
        if (app.globalData.cels) {
            that.setData({
                company: '摄氏度℃'
            })
        } else {
            that.setData({
                company: '华氏度℉'
            })
        }
    },

    // onTabItemTap(item) {
    // 	console.log(item.index)
    // 	console.log(item.pagePath)
    // 	console.log(item.text)

    // 	var that = this
    // 	that.putdata()
    // }


})
